<template>
  <div>
    <div class="tip">
      <i class="iconfont-sys icon">&#xe600;</i
      >请确保信息真实有效，不得冒用他人身份或驾校资质，一经发现将承担所有法律责任，并永久撤销该注册人平台使用资格。</div
    >
    <div class="form-area">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="驾校名称" prop="storeName">
          <el-input v-model="ruleForm.storeName" placeholder="请输入驾校名称" />
        </el-form-item>
        <el-form-item label="驾校LOGO">
          <el-input v-model="ruleForm.storeLogo" style="display: none"></el-input>

          <el-upload
            class="avatar-uploader"
            :action="server"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-image
              v-if="ruleForm.storeLogo"
              :src="ruleForm.storeLogo"
              class="avatar"
              fit="contain"
            ></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"
              ><el-icon><Plus /></el-icon
            ></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属区域" prop="area">
          <el-cascader
            ref="addressInfo"
            v-model="ruleForm.area"
            :options="addressOptions"
            @change="handleChange"
            :props="props"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="驾校简介" prop="storeDesc">
          <el-input v-model="ruleForm.storeDesc" type="textarea" :autosize="{ minRows: 8 }" />
        </el-form-item>
      </el-form>
    </div>

    <div class="step-btn">
      <el-button type="default" @click="goHome">返回首页</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">下一步</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { Plus } from '@element-plus/icons-vue'
  import { reactive, ref } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import { useTemporaryStore } from '@/store/modules/temporary'
  import { getAddressInfo } from '@/api/ApiList'
  const useTemporaryData = useTemporaryStore()

  const addressOptions = ref([])
  const props = ref({ value: 'code', label: 'name', children: 'children' })

  let server = `${import.meta.env.VITE_API_URL}files`
  const userStore = useUserStore()
  let { accessToken } = userStore
  const headers = { Authorization: 'Bearer ' + accessToken }
  const addressInfo = ref()

  const router = useRouter()

  const emit = defineEmits(['nextStep'])

  interface RuleForm {
    id?: string
    storeName: string
    storeLogo: string
    provinceCode: string
    provinceName: string
    cityCode: string
    cityName: string
    storeDesc: string
    areaCode: string
    areaName: string
    area?: any
  }

  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive<RuleForm>({
    storeName: '',
    storeLogo: '',
    provinceCode: '',
    provinceName: '',
    cityCode: '',
    cityName: '',
    areaCode: '',
    areaName: '',
    storeDesc: ''
  })

  const handleChange = (val: any) => {
    const areaText = addressInfo.value.presentText
    const addressSplit = areaText.split('/')
    ruleForm.provinceCode = val[0]
    ruleForm.provinceName = addressSplit[0]
    ruleForm.cityCode = val[1]
    ruleForm.cityName = addressSplit[1]
    ruleForm.areaCode = val[2]
    ruleForm.areaName = addressSplit[2]
  }

  const rules = reactive<FormRules<RuleForm>>({
    storeName: [{ required: true, message: '请输入驾校名称', trigger: 'blur' }],
    storeDesc: [
      {
        required: true,
        message: '请输入驾校简介',
        trigger: 'blur'
      }
    ]
  })

  const handleAvatarSuccess = (file: any) => {
    ruleForm.storeLogo = file.data.url
  }
  //上传限制大小格式等
  const beforeAvatarUpload = (file: any) => {
    const isLt2M = file.size / 10240 / 10240 < 2
    if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
      ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('上传头像图片大小不能超过 20MB!!')
      return false
    }
  }

  function goHome() {
    router.push('/drivingSchoolConsole/schoolConsole')
  }

  async function getAddressListData() {
    const res = await getAddressInfo()
    if (res.code === '00000') {
      addressOptions.value = res.data
    }
  }

  async function submitForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        useTemporaryData.setDrivingSchoolInfo(ruleForm)
        emit('nextStep')
      } else {
      }
    })
  }

  onMounted(() => {
    getAddressListData()

    let addData: Record<string, any> = useTemporaryData.getAddDrivingSchoolInfo()

    if (addData.storeName) {
      ruleForm.id = addData.id
      ruleForm.storeLogo = addData.storeLogo
      ruleForm.storeName = addData.storeName
      ruleForm.provinceCode = addData.provinceCode
      ruleForm.provinceName = addData.provinceName
      ruleForm.cityCode = addData.cityCode
      ruleForm.cityName = addData.cityName
      ruleForm.areaCode = addData.areaCode
      ruleForm.areaName = addData.areaName
      ruleForm.storeDesc = addData.storeDesc
      ruleForm.area = [addData.provinceCode, addData.cityCode, addData.areaCode]
    }
  })
</script>

<style scoped lang="scss">
  .tip {
    width: 100%;
    text-align: center;
    color: var(--el-color-primary);
    margin-bottom: 30px;
  }

  .form-area {
    width: 600px;
    margin: 0 auto;

    .avatar-uploader {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }

  .step-btn {
    display: flex;
    justify-content: center;
    align-items: center;

    margin-top: 20px;
  }
</style>
